package com.wu.leetcode.leetcode581;

import java.util.Arrays;

/**
 * Leetcode581-最短无序连续子数组
 *
 * @author lynn
 * @date 2020/11/4 - 9:55
 */
public class Solution {
    public static int findUnsortedSubarray(int[] nums) {
        int[] cop = nums.clone();
        Arrays.sort(cop);
        int left = nums.length, right = 0;

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != cop[i]) {
                left = Math.min(left, i);
                right = Math.max(right, i);
            }
        }
        return (right > left) ? right - left + 1 : 0; //返回结果
        //初始化
       /* int len = nums.length;
        int min = nums[len-1];
        int max = nums[0];
        int begin = 0, end = -1;
        //遍历
        for(int i = 0; i < len; i++){
            if(nums[i] < max){      //从左到右维持最大值，寻找右边界end
                end = i;
            }else{
                max = nums[i];
            }

            if(nums[len-i-1] > min){    //从右到左维持最小值，寻找左边界begin
                begin = len-i-1;
            }else{
                min = nums[len-i-1];
            }
        }
        return end-begin+1;*/
    }

    public static void main(String[] args) {
        int unsortedSubarray = findUnsortedSubarray(new int[]{2, 6, 4, 8, 10, 9, 15});
        System.out.println(unsortedSubarray);
    }
}
